/**
 *  Written by Tyler Montbriand in 2004
 *  100% freeware, do whatever the hell you want with it
 */

#include <stdlib.h>
#include <SDL/SDL.h>
#include <sidplay/sidtune.h>
#include <sidplay/emucfg.h>
#include "sdlext.h"

emuEngine engine;

void sid_callback(void *userdata, Uint8 *stream, int len);

int main(int argc, char *argv[])
{
  sidTune tune("Bulldog.sid");
  emuEngine engine;
  AudioSpec spec(44100,AUDIO_S16,1,1024,sid_callback,&tune);
  SDL_emucfg cfg(spec);

  if(argc!=2)
  {
    fprintf(stderr,"Syntax:  SDL_sidplay file.sid\n");
    return(1);
  }

  if(!tune.open(argv[1]))
  {
    fprintf(stderr,"Couldn't find file %s\n",argv[1]);
    return(1);
  }

  if(SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO)<0)
  {
    fprintf(stderr,"Couldn't init SDL: %s\n",SDL_GetError());
    return(1);
  }
  atexit(SDL_Quit);

  if(SDL_OpenAudio(&spec,NULL)<0)
  {
    fprintf(stderr,"Unable to open audio: %s\n",SDL_GetError());
    return(1);    
  }

  if(!engine.setConfig(cfg))
  {
    SDL_CloseAudio();
    fprintf(stderr,"Couldn't set emulation settings:\n");
    cfg.PrintSettings();
    return(1);
  }

  if(!sidEmuInitializeSong(engine,tune,0))
  {
    fprintf(stderr,"Couldn't initialize song!\n");
    SDL_CloseAudio();
    return(1);
  }

  SDL_PauseAudio(0);
  SDL_Delay(60*2*1000);
  SDL_PauseAudio(1);

  SDL_CloseAudio();
  
  return(0);
}

void sid_callback(void *userdata, Uint8 *stream, int len)
{
  sidTune *tune=(sidTune *)userdata;
  sidEmuFillBuffer(engine,(*tune),stream,len);
}
